#include "YasDownloadConfig.h"

namespace yas{

YasDownloadConfig::YasDownloadConfig(std::string baseURL, int port):
								baseUrl(baseURL),
								port(port)
{
}

YasDownloadConfig::YasDownloadConfig()
{
}

YasDownloadConfig::~YasDownloadConfig()
{
}

int YasDownloadConfig::loadConfigData(const std::string &fileLocation)
{
	std::fstream datafile(fileLocation.c_str(), std::fstream::in);
	char buffer[YasDownloadConfig::BUFSIZE];

	if(!datafile.good())
	{

		doLog("Cannot find configuration file " + fileLocation, Yas::YAS_ERROR);
		return Yas::YAS_ERROR;
	}
	else
	{
		while(datafile.good()){
			datafile.getline(buffer, YasDownloadConfig::BUFSIZE);
			std::string bufstr(buffer);
			size_t pos = -1;

			// If could not found `:' our simple syntax is wrong
			if((pos = bufstr.find(":")) == std::string::npos)
			{
				doLog("Invalid data at configuration file " + fileLocation, Yas::YAS_WARNING);
				continue;
			}

			std::string data = bufstr.substr(pos, bufstr.length()-pos);

			if((pos = bufstr.find("BASE_URL:")) > 0)
			{
				setBaseURL(data);
			}
			else if((pos = bufstr.find("PORT:")) > 0)
			{
				std::stringstream portstr(data);
				int port;
				portstr >> port;
				setPort(port);
			}

			else if((pos = bufstr.find("PATH:")) > 0)
			{
				addPath(data);
			}
			else if((pos = bufstr.find("KEYWORD:")) > 0)
			{
				addKeyword(data);
			}
			else{
				doLog("Invalid data field type:" + bufstr, Yas::YAS_WARNING);
			}

		}
	}
	datafile.close();
	return Yas::YAS_OK;
}


void YasDownloadConfig::addPath(const std::string url)
{
	this->paths.push_back(url);
}

void YasDownloadConfig::addKeyword(const std::string keyword)
{
	this->keywords.push_back(keyword);
}
}
